package com.android.bookgarden.ui;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.bookgarden.MainActivity;
import com.android.bookgarden.R;
import com.android.bookgarden.adapter.CollectionAdapter;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.CollecitonBean;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.HomeDataBean;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.recycleview.BaseViewHolder;
import com.android.bookgarden.recycleview.EndLessOnScrollListener;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.LoadingDialog;
import com.lzy.okgo.model.HttpHeaders;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class CollectionActivity extends BaseActivity implements View.OnClickListener ,RealtConstract.View {

    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @BindView(R.id.ritgh_text)
    TextView ritghText;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.allSelect)
    CheckBox allSelect;
    @BindView(R.id.deleteAll)
    TextView deleteAll;
    @BindView(R.id.editLayout)
    LinearLayout editLayout;
    private CollectionAdapter adapter;
    private List<HomeDataBean> list;
    private List<HomeDataBean> beanList;
    private RealtConstract.Presenter presenter;
    private int pageIndex = 1;
    private int pageSize = 20;
    private boolean isEdit;
    private String deleteId;
    private boolean flag = false;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_collection;
    }

    @Override
    protected void initView() {
        presenter = new BasePersenter(this,this);
        titleText.setText("我的收藏");
        ritghText.setText("管理");
        ritghText.setVisibility(View.VISIBLE);
        ritghText.setOnClickListener(this);
        close.setOnClickListener(this);
        allSelect.setOnClickListener(this);
        deleteAll.setOnClickListener(this);
        list = new ArrayList<>();
        beanList = new ArrayList<>();
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        list.add(new CollecitonBean("毕节市最好指尖芭蕾少儿舞蹈学校", "1223", false));
//        beanList.addAll(list);
        adapter = new CollectionAdapter(list, this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(manager);
        recycler.setHasFixedSize(true);
        recycler.setAdapter(adapter);
        adapter.addFooterView(R.layout.layout_footer);
//        adapter.addHeaderView(R.layout.home_layout_header,advList);

        recycler.addOnScrollListener(new EndLessOnScrollListener(manager) {
            @Override
            public void onLoadMore() {
                if (flag){
                    pageIndex ++;
                    if (list.size() != 0)
                        adapter.setFooterVisible(View.VISIBLE);
                    getDataList();
                }
            }
        });
        adapter.setOnItemClickLitener(new CollectionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, BaseViewHolder viewHolder) {
                HomeDataBean bean =  list.get(position);
                if (isEdit){
                   if (bean.isSelect()){
                       list.get(position).setSelect(false);
                   }else{
                       list.get(position).setSelect(true);
                   }
                    selectAll();
                  adapter.notifyDataSetChanged();

                }
            }
        });
        getDataList();

        allSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                noAllSelect(isChecked);
            }
        });

    }
    //判断是否全选
    private void selectAll(){
        int a =0;
        for (int i = 0; i <list.size() ; i++) {
            if (list.get(i).isSelect()){
                a++;
            }
        }

        if (a==list.size()){
            allSelect.setChecked(true);
        }else{
            allSelect.setChecked(false);
        }
    }

    //全选或全不选
    private void noAllSelect(boolean isCheak){
        for (int i = 0; i <list.size() ; i++) {
            if (isCheak){
                list.get(i).setSelect(true);
            }else{
                list.get(i).setSelect(false);
            }
        }
        adapter.notifyDataSetChanged();

    }

    //删除收藏
    private void deleteColletion(){
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isSelect()){
                buffer.append(list.get(i).getId()).append(",");
            }
        }
        if (buffer.toString().length()>1){
            buffer.deleteCharAt(buffer.length() - 1);
            deleteId = buffer.toString();
            List<HomeDataBean> bs = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                HomeDataBean bean = list.get(j);
                if (bean.isSelect()){
                  bs.add(bean);
                }
            }
            list.removeAll(bs);
            adapter.notifyDataSetChanged();

        }else{
            return;
        }

    }

    private void getDataList() {
        LoadingDialog.showMassge(this,"加载中...");
        presenter.loadDataHeader(null, "", Apis.COLLECTION_LIST + pageIndex + "/" + pageSize + "/1", 1002, Utlis.getHeadler(this), HttpType.GET);
    }

    @Override
    public void onRequestPermissions(String str, boolean z) {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                if (isEdit){
                    isEdit = false;
                    ritghText.setText("编辑");
                    editLayout.setVisibility(View.GONE);

//                    list.addAll(beanList);
//                    beanList.clear();
                    if (!TextUtils.isEmpty(deleteId)){
                        LoadingDialog.showMassge(this,"删除中...");
                        presenter.loadDataHeader(null, "", Apis.COLLECTION_DELETE  + "1/" + deleteId, 1003, Utlis.getHeadler(this), HttpType.DELETE);

                    }

                }else{
                    flag = false;
                    isEdit = true;
                    ritghText.setText("完成");
                    editLayout.setVisibility(View.VISIBLE);

                }

                adapter.isEdit(isEdit);
                adapter.notifyDataSetChanged();

                break;

            case R.id.deleteAll:
                deleteColletion();
                break;
        }
    }


    @Override
    public void returnData(String data, int urlCode) {
        LogUtil.e("返回数据", data + "");
        if (TextUtils.isEmpty(data)) {
            return;
        }
        LoadingDialog.hideProgress();
        handler.obtainMessage(urlCode, data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        showToast("请求失败");
        LoadingDialog.hideProgress();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            switch (msg.what) {
                case 1001:
                    try {
                        LoadingDialog.hideProgress();
                        DataBean bean = Utlis.getDataBean(data);
                        showToast(bean.getMessage());
                        if (bean.getCode() == 200) {
                            finish();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case 1002:
//                    refreshLayout.setRefreshing(false);
                    DataBean bean = Utlis.getDataBean(data);
                    if (null == bean) {
                        showToast("获取列表失败");
                        return;
                    }
                    if (bean.getCode() == 200) {
                        List<HomeDataBean> listD = JsonUitl.stringToList(bean.getData(), HomeDataBean.class);
                        if (null == listD || listD.size() <= 0) {
                            adapter.setFooterVisible(View.GONE);
                            flag = false;
                            return;
                        }
                        list.addAll(listD);
                        adapter.notifyDataSetChanged();
                        if (listD.size()<pageSize){
                            adapter.setFooterVisible(View.GONE);
                            flag = false;
                        }else {
                            flag = true;
                        }

                    } else {
                        showToast(bean.getMessage() + "");
                    }


                    break;

                case 1003:
                    try {

                         bean = Utlis.getDataBean(data);
                        showToast(bean.getMessage());
                        if (bean.getCode() == 200) {
                            list.clear();
                            isEdit = false;
                            adapter.isEdit(isEdit);
                            deleteId ="";
                           getDataList();
                        }else{
                            LoadingDialog.hideProgress();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

            }
        }
    };
}
